<template>
  <!-- 新增优惠券 -->
  <div class="content">
    <h2 class="u-title-h2">优惠券（新增 / 编辑）</h2>
    <div class="u-form-box">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="140px"
        class="demo-ruleForm"
      >
        <el-form-item label="优惠券名称：" prop="name">
          <el-input
            :disabled="isDisabled"
            v-model="ruleForm.name"
            placeholder="请输入优惠券名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="优惠券类型：" prop="coupon_type">
          <el-select
            :disabled="isDisabled"
            v-model="ruleForm.coupon_type"
            placeholder="请选择优惠券类型："
          >
            <el-option
              v-for="(item, index) in selectArr.coupon_type"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预付：" prop="price">
          <el-input
            oninput="this.value=this.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3')"
            type="number"
            min="0"
            :disabled="isDisabled"
            v-model="ruleForm.price"
            placeholder="请输入预付价格"
          ></el-input>
        </el-form-item>
        <!-- prop="text"
        :rules="[{ required: true, message: '请输入'+item.label+'价格', trigger: 'blur' }]"-->

        <el-form-item
          v-for="(item, index) in selectArr.discount_type"
          :key="index"
          :label="item.label + '：'"
        >
          <el-input
            :disabled="isDisabled"
            oninput="this.value=this.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3')"
            type="number"
            min="0"
            v-model="item.text"
            :placeholder="'请输入' + item.label + '价格'"
          ></el-input>
        </el-form-item>
        <!-- <el-form-item label>
          <el-button type="primary" @click="addCourse" icon="el-icon-plus" circle></el-button>
          <el-button type="danger" @click="deleteCourse" icon="el-icon-minus" circle></el-button>
        </el-form-item>-->
        <el-form-item label="优惠券失效时间：" prop="expire_time">
          <el-date-picker
            class="u-time-box"
            v-model="ruleForm.expire_time"
            :editable="false"
            :placeholder="'请选择优惠券失效时间'"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            @change="changeListTime"
            :picker-options="pickerOptions"
          ></el-date-picker>
        </el-form-item>
        <!-- <el-form-item label="抢券开始时间：" prop="list_time">
          <el-date-picker
            class="u-time-box"
            v-model="ruleForm.list_time"
            :editable="false"
            :placeholder="earliestTime?'选择日期时间(不晚于'+ earliestTime +')':'选择日期时间'"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            @change="changeListTime"
            :picker-options="pickerOptions"
          ></el-date-picker>
        </el-form-item>-->
        <el-form-item label="抢券结束时间：" prop="end_time">
          <el-date-picker
            :disabled="!ruleForm.expire_time"
            class="u-time-box"
            v-model="ruleForm.end_time"
            :editable="false"
            :placeholder="
              ruleForm.expire_time
                ? '选择日期时间(不晚于' + ruleForm.expire_time + ')'
                : '请先选择优惠券失效时间'
            "
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            @change="setEndTime"
            :picker-options="pickerOptions"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-checkbox
            :disabled="true"
            v-model="ruleForm.purchase_restrictions_type"
            >每人限制购买1次</el-checkbox
          >
        </el-form-item>
        <el-form-item>
          <el-button
            :disabled="isDisabled"
            type="primary"
            @click="submitForm('ruleForm', 0)"
            >保存</el-button
          >
          <!-- <el-button @click="resetForm('ruleForm')">重置</el-button> -->
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import {
  queyEnumByTableName,
  ossUpload,
  tableInsert
  // tableUpdate
} from '@/api/api.js'
import {
  addCoupon,
  getActivityCouponResource,
  getCouponDetail
} from '@/api/coupon.js'
export default {
  name: 'add-update-class',
  data () {
    var levelRule = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择难度'))
      } else {
        callback()
      }
    }
    return {
      isDisabled: false,
      pickerOptions: {
        disabledDate (date) {
          return date.getTime() < Date.now() - 8.64e7
        }
      },
      earliestTime: '',
      isOpen: false,
      gradeCopy: null,
      gradeLabel: '全部',
      showRentPrise: false,
      percentage: 0,
      ismultiple: false,
      selectArr: {
        coupon_type: [],
        discount_type: []
      },
      ruleForm: {
        name: '',
        coupon_type: '',
        price: '',
        expire_time: '',
        end_time: '',
        purchase_restrictions_type: true
      },
      rules: {
        coupon_type: [
          { required: true, message: '请选择优惠券类型', trigger: 'change' }
        ],
        name: [
          { required: true, message: '请输入优惠券名称', trigger: 'blur' }
          // { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入预付价格', trigger: 'blur' }
          // { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' }
        ],
        end_time: [
          { required: true, message: '请选择抢券结束时间', trigger: 'change' }
        ],
        expire_time: [
          { required: true, message: '请选择优惠券失效时间', trigger: 'change' }
        ]
      }
    }
  },
  watch: {},
  created () {},
  activated () {
    this.$route.query.id ? (this.isDisabled = true) : (this.isDisabled = false)
    this.getSelectData()
  },
  methods: {
    setEndTime (e) {
      if (this.ruleForm.expire_time < this.ruleForm.end_time) {
        this.ruleForm.end_time = ''
        this.$message({
          message: '结束时间不得晚于优惠券失效时间',
          type: 'warning'
        })
      }
    },
    // 获取下拉菜单数据
    async getSelectData () {
      this.ruleForm = {
        name: '',
        coupon_type: '',
        price: '',
        expire_time: '',
        end_time: '',
        purchase_restrictions_type: true
      }
      this.$refs.ruleForm.resetFields()
      let res = await getActivityCouponResource({})
      if (res[0]) {
        return
      }
      let arr = res[1].data
      Object.keys(this.selectArr).forEach(item => {
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].fieldName === item) {
            this.selectArr[item] = arr[i].sourceData.child
          }
        }
      })
      this.selectArr = JSON.parse(
        JSON.stringify(this.selectArr)
          .split('display_value')
          .join('label')
          .split('child')
          .join('children')
          .split('t_id')
          .join('value')
      )
      this.selectArr.discount_type.map(item => {
        item.text = ''
      })
      this.selectArr = JSON.parse(JSON.stringify(this.selectArr))
      if (this.isDisabled) {
        this.getCouponDetailFn()
      }
    },
    async getCouponDetailFn () {
      let res = await getCouponDetail({
        'nice_activity_coupon.id': this.$route.query.id
      })
      if (res[0]) {
        return
      }
      let data = res[1].data.list[0]
      this.ruleForm = {
        name: data.name,
        coupon_type: data.coupon_type,
        price: data.price,
        expire_time: data.expire_time,
        end_time: data.end_time,
        purchase_restrictions_type: true
      }
      let arr = JSON.parse(data.discount_info)
      this.selectArr.discount_type.map((item, index) => {
        item.text = arr[index].price
      })
      console.log(res[1], 'ssss')
    },
    addCourse () {
      this.ruleForm.course_id.push('')
      this.ruleForm.course_time_id.push([])
    },
    deleteCourse () {
      if (this.ruleForm.course_id.length > 1) {
        this.ruleForm.course_id.pop()
        this.ruleForm.course_time_id.pop()
      }
    },
    changeListTime () {
      this.ruleForm.end_time = ''
    },
    changeTerm (e) {
      this.gradeCopy = e
    },
    changeGrade (e, carate) {
      if (carate !== 'carate') {
        this.ruleForm.term = ''
      }
      if (e === null) {
        this.gradeLabel = '全部'
      } else {
        this.selectArr.grade.map(item => {
          if (item.value === e) {
            this.gradeLabel = item.label
          }
        })
      }
    },
    // 根据id获取课程信息
    async getCourseByIdFn () {
      let res = await getCourseById({
        table_name: 'nice_course',
        id: this.$route.query.id
      })
      if (res[0]) {
        return
      }
      let data = res[1].data
      console.log(data, 'asdasdasdsadsads')
      this.ruleForm.name = data.name
      this.ruleForm.type = data.type
      this.ruleForm.grade = data.grade
      this.gradeCopy = data.grade
      this.ruleForm.term = data.term
      this.ruleForm.subject = data.subject
      this.ruleForm.cover_path = data.cover_path
      this.ruleForm.poster_path = data.poster_path
      this.ruleForm.level = data.level
      this.ruleForm.description = data.description
      this.ruleForm.introduction_video = data.introduction_video
      this.ruleForm.has_teaching_materials = data.has_teaching_materials
      this.changeGrade(this.ruleForm.grade, 'carate')
      let arr = data.version.split(',')
      let newArr = []
      arr.map(item => {
        newArr.push(parseInt(item))
      })
      this.ruleForm.versionArr = [...newArr]
      this.ruleForm.version = newArr[0]
      console.log(this.ruleForm, 'arrarrarrarr')
    },

    // 表单验证
    // 新增课程信息请求
    async addCouponFn () {
      let arr = []
      this.selectArr.discount_type.map((item, index) => {
        arr.push({
          type: item.value,
          price: item.text,
          sort_no: index + 1
        })
      })
      if (!arr[0].price) {
        this.$message({
          message: '至少填写一项抵扣价格',
          type: 'warning'
        })
        return
      }
      let res = await addCoupon({
        'nice_activity_coupon.name': this.ruleForm.name,
        'nice_activity_coupon.coupon_type': this.ruleForm.coupon_type,
        'nice_activity_coupon.price': this.ruleForm.price,
        'nice_activity_coupon.expire_time': this.ruleForm.expire_time,
        'nice_activity_coupon.end_time': this.ruleForm.end_time,
        'nice_activity_coupon.purchase_restrictions_type': this.ruleForm
          .purchase_restrictions_type
          ? 1
          : 0,
        'nice_activity_coupon_and_discount.array': arr
      })
      if (res[0]) {
        return
      }
      this.$message({
        message: '保存优惠券成功',
        type: 'success'
      })
      this.$router.push({ name: 'coupon' })
    },
    // 修改课程信息请求
    async updateCoures () {
      let version
      this.ismultiple
        ? (version = this.ruleForm.versionArr.join(','))
        : (version = this.ruleForm.version)
      let res = await updateCourse([
        {
          table_name: 'nice_course',
          update: [
            {
              name: this.ruleForm.name, // --
              type: this.ruleForm.type, // -- 分类
              grade: this.ruleForm.grade, // -- 年级
              subject: this.ruleForm.subject, // -- 科目
              version: version, // -- 版本
              // time: 8, // --
              term: this.ruleForm.term,
              cover_path: this.ruleForm.cover_path,
              introduction_video: this.ruleForm.introduction_video,
              poster_path: this.ruleForm.poster_path,
              level: this.ruleForm.level, // -- 课程难度
              description: this.ruleForm.description, // --简介
              status: this.ruleForm.status, // --  0 保存 1 保存并发布
              has_teaching_materials: this.ruleForm.has_teaching_materials
            }
          ],
          where: [
            {
              id: this.$route.query.id
            }
          ]
        }
      ])
      if (res[0]) {
        return
      }
      this.$router.push({ name: 'class-list' })
      console.log(res[1])
    },

    submitForm (formName, e) {
      this.ruleForm.status = e
      this.$refs[formName].validate(valid => {
        if (valid) {
          // 新增课程
          // if (!this.$route.query.id) {
          this.addCouponFn()
          // } else {
          // 修改课程
          // this.updateCoures()
          // }
        } else {
          return false
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    randomString () {
      let len = 7
      let $chars =
        'ABCDEFGHJKMNPQRSTWXYZ0123456789' /** **默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
      let maxPos = $chars.length
      let pwd = ''
      for (let i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
      }
      return pwd
    }
  }
}
</script>
<style scoped>
h2 {
  padding-left: 20px;
}
.u-form-box {
  width: 670px;
  padding-bottom: 50px;
}
.u-form-item-rate {
  padding-top: 9px;
}
.cascader {
  width: 100%;
}
.u-title-h2 {
  padding-left: 70px;
  margin-bottom: 40px;
}
.optionShow {
  display: none;
}
.u-time-box {
  width: 400px;
}
.u-info-text {
  font-size: 12px;
}
</style>
